package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.article.domain.ItemShop;
import cn.wolfcode.luowowo.article.service.IItemShopService;
import cn.wolfcode.luowowo.comment.domain.UserGoods;
import cn.wolfcode.luowowo.comment.query.UserGoodsQuery;
import cn.wolfcode.luowowo.comment.repository.UserGoodsRepository;
import cn.wolfcode.luowowo.comment.service.IUserGoodsService;
import cn.wolfcode.luowowo.member.domain.UserInfoScore;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class UserGoodsServiceImpl implements IUserGoodsService {
    @Autowired
    private UserGoodsRepository repository;
    @Autowired
    private MongoTemplate template;
    @Reference
    private IItemShopService iItemShopService;

    @Override
    public void save(UserGoods userGoods) {

        repository.save( userGoods );
    }

    @Override
    public Page <UserGoods> query(UserGoodsQuery qo) {
        Query query = new Query();
        query.addCriteria( Criteria.where( "userId" ).is( qo.getUserId()) );
        //查count
        long total = template.count( query, UserGoods.class );
        if (total == 0) {
            return Page.empty();
        }
        //查list
        //添加分页
        Pageable pageable = PageRequest.of( qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "date");
        query.with( pageable );
        List <UserGoods> userGoodss = template.find( query, UserGoods.class );
        return new PageImpl <>( userGoodss, pageable, total );
    }

    @Override
    public void cashGift(Long id, ItemShop itemShop) {
        ItemShop shop = iItemShopService.get(itemShop.getId());
        UserGoods userGoods = new UserGoods();
        userGoods.setImgUrl(shop.getImgUrl());
        userGoods.setInfo(shop.getInfo());
        userGoods.setItemShopId(shop.getId());
        userGoods.setName(shop.getName());
        userGoods.setRest(shop.getRest());
        userGoods.setUserId(id);
        userGoods.setDate( new Date() );
        repository.save(userGoods);

    }

}
